package com.lancoo.cvas.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lancoo.cvas.entity.UserSetting;
import com.lancoo.cvas.mapper.UserSettingMapper;
import com.lancoo.cvas.service.UserSettingService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;


@Service("userSettingService")
public class UserSettingServiceImpl extends ServiceImpl<UserSettingMapper, UserSetting> implements UserSettingService {


    @Resource
    private UserSettingMapper userSettingMapper;

    @Override
    public UserSetting getUserSettingByUserId(String userId) {
        List<UserSetting> userSettingList = this.lambdaQuery().eq(UserSetting::getUserId, userId).list();
        //优先显示已设置任务配置 没有则显示第一条
        Optional<UserSetting> userSetting = userSettingList.stream().filter(a -> a.getIsCurrent().equals(1)).findFirst();
        if (!userSetting.isPresent()) {
            userSetting = userSettingList.stream().findFirst();
        }
        return userSetting.orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserSetting(UserSetting userSetting) {
        //先删除所有非当前任务
        this.lambdaUpdate().eq(UserSetting::getUserId,userSetting.getUserId()).remove();
        //再生成当前任务
        userSetting.setIsCurrent(1);

        return userSettingMapper.insertUserSetting(userSetting.getUserId()
                , ObjUtil.isNotNull(userSetting.getTaskId()) ? userSetting.getTaskId() : 0, userSetting.getIsCurrent(), userSetting.getColor(), userSetting.getSidebar()) > 0;

    }
}